#include "fbd.h"
#include "../log.h"

FileBlockDevice fbd_init(const char *filename)
{
    FileBlockDevice fbd;
    fbd.f = fopen(filename, "rb");
    if (!fbd.f)
        _log(ERR, FS, "Error loading '%s' in FileBlockDevice!", filename);

    fseek(fbd.f, 0, SEEK_END);
    fbd.filesize = ftell(fbd.f);
    fseek(fbd.f, 0, SEEK_SET);
    return fbd;
}

void fbd_free(FileBlockDevice *fbd)
{
    if (fbd->f)
        fclose(fbd->f);
    fbd->f = NULL;
}

void fbd_readBlock(FileBlockDevice *fbd, u32 blockNumber, char *outPtr)
{
    u32 n;
    fseek(fbd->f, blockNumber * fbd_getBlockSize(), SEEK_SET);
    if ((n = fread(outPtr, 2048, 1, fbd->f)) != 1)
        _log(ERR, FS, "Error reading block with fbd_readBlock() at block %d [offset %08x]: got %d", blockNumber, blockNumber * fbd_getBlockSize(), n);
}

u32 fbd_getNumBlocks(FileBlockDevice *fbd) {
    return fbd->filesize / fbd_getBlockSize();
}

u32 fbd_getBlockSize() {
    return 2048;
}

